package com.tsugun.mediaplayer.view.fragment.subfragment;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.tsugun.mediaplayer.R;
import com.tsugun.mediaplayer.model.entity.MusicModel;
import com.tsugun.mediaplayer.model.entity.SheetModel;
import com.tsugun.mediaplayer.presenter.provider.ListProvider;
import com.tsugun.mediaplayer.view.activity.IndexActivity;
import com.tsugun.mediaplayer.view.adapter.MusicCardItemAdapter;
import com.tsugun.mediaplayer.view.adapter.MusicFeatureItemAdapter;
import com.tsugun.mediaplayer.view.adapter.MusicMenuAdapter;
import com.tsugun.mediaplayer.view.adapter.SheetItemMenuAdapter;
import com.tsugun.mediaplayer.view.adapter.SwitcherAdapter;
import com.tsugun.mediaplayer.view.widget.MusicMenuDialog;
import com.tsugun.mediaplayer.view.widget.ViewSwitcher;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * create an instance of this fragment.
 */
public class FeatureFragment extends SubBaseFragment implements ViewPager.OnPageChangeListener, MusicMenuAdapter.OnMenuItemClickListener {

    @BindView(R.id.id_image_switcher)
    ViewSwitcher mViewSwitcher;// 图片切换器
    @BindViews({R.id.id_switcher_point1, R.id.id_switcher_point2, R.id.id_switcher_point3,
            R.id.id_switcher_point4, R.id.id_switcher_point5})
    ImageView[] mIvPoints = new ImageView[5];
    @BindView(R.id.id_recycler_you_may_like)
    RecyclerView mRvMayLike;// 猜你喜欢
    @BindView(R.id.id_change_may_like)
    TextView mTvLike;
    @BindView(R.id.id_recycler_feature)
    RecyclerView mRvFeature;// 推荐歌曲
    @BindView(R.id.id_change_feature)
    TextView mTvFeature;

    private View mFragment;
    private Context mContext;
    private Unbinder unbinder;
    private ListProvider mProvider;
    private IndexActivity indexActivity;

    private SwitcherAdapter mSwitcherAdapter;
    private MusicCardItemAdapter mMayLikeAdapter;
    private List<MusicModel> mMusicMayLike; // 猜你喜欢
    private MusicFeatureItemAdapter mFeatureAdapter;
    private List<MusicModel> mMusicFeature; // 推荐
    private int mCurrentIndex;// 当前显示的图片
    // 菜单
    private int mPosition; // 点击菜单项位置
    private MusicMenuDialog mDialog; // 菜单弹出框
    private List<String> mMenuList; // 菜单列表项目
    private MusicMenuAdapter mMenuAdapter; // 菜单适配器
    // 添加歌单
    private String mTitle; // 歌曲标题
    private List<SheetModel> mSheets; // 歌单列表

    private SheetItemMenuAdapter mSheetAdapter;
    private MusicMenuDialog mSheetDialog;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mFragment = inflater.inflate(R.layout.fragment_feature, container, false);
        mContext = container.getContext();
        unbinder = ButterKnife.bind(this, mFragment);

        initData();
        bindData();
        return mFragment;
    }

    /**
     * 初始化数据
     */
    private void initData() {
        mCurrentIndex = 0;
        mMusicMayLike = new ArrayList<>();
        mMusicFeature = new ArrayList<>();
        int[] mImgId = new int[]{R.mipmap.feature_01, R.mipmap.feature_02,
                R.mipmap.feature_03, R.mipmap.feature_04, R.mipmap.feature_02};
        mSwitcherAdapter = new SwitcherAdapter(mContext, mImgId, mViewSwitcher);
        indexActivity = (IndexActivity) getActivity();
        mProvider = indexActivity.getListProvider();
    }

    /**
     * 绑定数据
     */
    private void bindData() {
        mViewSwitcher.setAdapter(mSwitcherAdapter);
        mViewSwitcher.addOnPageChangeListener(this);
//        initYouMayLike();
//        initFeature();
        mTvLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initYouMayLike();
            }
        });
        mTvFeature.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initFeature();
            }
        });
        initYouMayLike();
        initFeature();
        initFeatureMenu();
    }

    /**
     * 点亮和熄灭points
     */
    private void lightUpPoint() {
        for (ImageView mIvPoint : mIvPoints) {
            mIvPoint.setImageResource(R.drawable.ic_point_black);
        }
        mIvPoints[mCurrentIndex].setImageResource(R.drawable.ic_point_light);
    }

    /**
     * 初始化猜你喜欢列表
     */
    private void initYouMayLike() {
        if (mProvider == null) {
            return;
        }
        Collection<MusicModel> models = (Collection<MusicModel>) mProvider.searchAllMusic();
        mayLikeMusic(models);
        mMayLikeAdapter = new MusicCardItemAdapter(mContext, mMusicMayLike);
        mMayLikeAdapter.setOnMusicCardClickListener(
                new MusicCardItemAdapter.OnMusicCardClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        indexActivity.playMusicById(mMusicMayLike.get(position).getId());
                    }
                });
        mRvMayLike.setAdapter(mMayLikeAdapter);
        mRvMayLike.setLayoutManager(new LinearLayoutManager(mContext,
                LinearLayoutManager.HORIZONTAL, false));
        mRvMayLike.startLayoutAnimation();

        setSettingTheme(mRvMayLike);
    }

    /**
     * 初始化推荐歌曲列表
     */
    private void initFeature() {
        if (mProvider == null) {
            return;
        }
        Collection<MusicModel> models = (Collection<MusicModel>) mProvider.searchAllMusic();
        featureMusic(models);
        mFeatureAdapter = new MusicFeatureItemAdapter(mContext, mMusicFeature);
        mFeatureAdapter.setOnMusicItemClickListener(
                new MusicFeatureItemAdapter.OnMusicItemClickListener() {
                    @Override
                    public void onItemClick(int position) {
                        indexActivity.playMusicById(mMusicFeature.get(position).getId());
                    }

                    @Override
                    public void onMenuClick(int position) {
                        mPosition = position;
                        showMenu();
                    }
                });
        mRvFeature.setAdapter(mFeatureAdapter);
        mRvFeature.setLayoutManager(new LinearLayoutManager(mContext,
                LinearLayoutManager.VERTICAL, false));
        mRvFeature.startLayoutAnimation();
        setSettingTheme(mRvFeature);
    }

    /**
     * 初始化菜单
     */
    private void initFeatureMenu() {
        // 当前点击位置
        mPosition = 0;
        // 菜单项目标题
        mMenuList = new ArrayList<>();
        mMenuList.add(getString(R.string.str_menu_item_next));
        mMenuList.add(getString(R.string.str_menu_item_collection));
        mMenuList.add(getString(R.string.str_menu_item_artist));
        mMenuList.add(getString(R.string.str_menu_item_album));
        mMenuList.add(getString(R.string.str_menu_item_details));
        // 菜单项图标
        int[] mIcons = new int[]{R.drawable.ic_menu_item_next, R.drawable.ic_menu_item_collection,
                R.drawable.ic_menu_item_artist, R.drawable.ic_menu_item_album,
                R.drawable.ic_menu_item_details};
        // 菜单点击事件
        mMenuAdapter = new MusicMenuAdapter(mContext, mMenuList, mIcons);
        mMenuAdapter.setOnMenuClickListener(this);
    }

    @Override
    public void onMenuClick(int pos) {
        // 菜单项点击事件
        switch (pos) {
            case MENU_ITEM_NEXT_PLAY:
                indexActivity.setNextPlayMusic(mMusicFeature.get(mPosition).getId());
                break;
            case MENU_ITEM_COLLECTION:
                showSheetList();
                break;
            case MENU_ITEM_ARTIST:
                startArtistFragment(mMusicFeature.get(mPosition).getArtist());
                break;
            case MENU_ITEM_ALBUM:
                startAlbumFragment(mMusicFeature.get(mPosition).getAlbum());
                break;
            case MENU_ITEM_INFO:
                showMusicInfoDialog(mMusicFeature.get(mPosition));
                break;
        }
        mDialog.dismiss();
    }

    /**
     * 显示歌单会话框
     */
    private void showSheetList() {
        mSheets = new ArrayList<>();
        mSheets.addAll((Collection<? extends SheetModel>) mProvider.getSheet());
        mSheetAdapter = new SheetItemMenuAdapter(mContext, mSheets);
        mSheetAdapter.setProvider(mProvider);
        mSheetAdapter.setOnSheetItemClickListener(new SheetItemMenuAdapter.OnSheetItemClickListener() {
            @Override
            public void onItemClick(int position) {
                mSheetDialog.dismiss();
                addMusicToSheet(position);
            }
        });
        MusicMenuDialog.Builder builder = new MusicMenuDialog.Builder(mContext, mSheetAdapter, mTitle);
        mSheetDialog = builder.create();
        mSheetDialog.show();
    }

    /**
     * 添加音乐到歌单
     */
    private void addMusicToSheet(int position) {
        SheetModel oldSheet = mSheets.get(position);
        List<String> strId = oldSheet.getMusicIdList();
        String sheetId = mMusicFeature.get(mPosition).getId();
        if (strId.contains(sheetId)) {
            Snackbar.make(mRvFeature, R.string.str_duplicate_music, Snackbar.LENGTH_LONG).show();
            return;
        }
        strId.add(sheetId);
        mProvider.editSheetAddMusic(oldSheet, strId);
        mSheets.remove(oldSheet);
        oldSheet.setMusicIdList(strId);
        mSheets.add(oldSheet);
        // 更新歌单列表
        indexActivity.updateSheetList();
        Snackbar.make(mRvFeature, R.string.str_add_complete, Snackbar.LENGTH_LONG).show();
    }

    /**
     * 显示歌曲菜单
     */
    private void showMenu() {
        mTitle = getString(R.string.str_music) + mMusicFeature.get(mPosition).getTitle();
        // 初始化菜单项目歌手和专辑显示
        mMenuList.remove(MENU_ITEM_ARTIST);
        mMenuList.add(MENU_ITEM_ARTIST, getString(R.string.str_menu_item_artist)
                + mMusicFeature.get(mPosition).getArtist());
        mMenuList.remove(MENU_ITEM_ALBUM);
        mMenuList.add(MENU_ITEM_ALBUM, getString(R.string.str_menu_item_album)
                + mMusicFeature.get(mPosition).getAlbum());
        MusicMenuDialog.Builder builder = new MusicMenuDialog.Builder(mContext, mMenuAdapter
                , mTitle);
        mDialog = builder.create();
        mDialog.show();
    }

    /**
     * 获取推荐的音乐
     *
     * @param models 数据源
     */
    private void featureMusic(Collection<MusicModel> models) {
        mMusicFeature = new ArrayList<>();
        if (models.size() < 3) {
            mMusicFeature.addAll(models);
            return;
        }
        randFeatureMusic(models);
    }

    /**
     * 随机获取音乐文件
     *
     * @param models 数据源
     */
    private void randFeatureMusic(Collection<MusicModel> models) {
        List<MusicModel> list = new ArrayList<>();
        list.addAll(models);
        int index = (int) (Math.random() * list.size());
        mMusicFeature.clear();
        for (int i = 0; i < 3; i++) {
            mMusicFeature.add(list.get((index + i) % list.size()));
        }
    }

    /**
     * 获取可能喜欢的音乐
     *
     * @param models 数据源
     */
    private void mayLikeMusic(Collection<MusicModel> models) {
        mMusicMayLike = new ArrayList<>();
        if (models.size() < 5) {
            mMusicMayLike.addAll(models);
            return;
        }
        randLikeMusic(models);
    }

    /**
     * 随机获取音乐文件
     *
     * @param models 数据源
     */
    private void randLikeMusic(Collection<MusicModel> models) {
        List<MusicModel> list = new ArrayList<>();
        list.addAll(models);
        int index = (int) (Math.random() * list.size());
        mMusicMayLike.clear();
        for (int i = 0; i < 5; i++) {
            mMusicMayLike.add(list.get((index + i) % list.size()));
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mCurrentIndex = position;
        lightUpPoint();
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        mViewSwitcher.isTouch(state != ViewPager.SCROLL_STATE_IDLE);
    }

    @Override
    public void onDestroyView() {
        mViewSwitcher.close();
        super.onDestroyView();
        unbinder.unbind();
    }
}
